<?php

namespace yii\authclient\clients;

use yii\authclient\OAuth2;

class Weixin extends OAuth2 {

    public $authUrl = 'https://open.weixin.qq.com/connect/qrconnect';
    public $tokenUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token';
    public $apiBaseUrl = 'https://api.weixin.qq.com';

    public function init() {
        parent::init();
        if ($this->scope === NULL) {
            $this->scope = implode(' ', ['snsapi_login']);
        }
    }

    public function buildAuthUrl(array $params = []) {
        $defaultParams = [
            'appid' => $this->clientId,
            'redirect_uri' => $this->getReturnUrl(),
            'response_type' => 'code',
            'scope' => $this->scope,
            'state' => substr(time(), 8, 4),
        ];
        return $this->composeUrl($this->authUrl, array_merge($defaultParams, $params)) . '#wechat_redirect';
    }

    public function fetchAccessToken($authCode, array $params = []) {
        $params['appid'] = $this->clientId;
        $params['secret'] = $this->clientSecret;
        return parent::fetchAccessToken($authCode, $params);
    }

    protected function apiInternal($accessToken, $url, $method, array $params, array $headers) {
        $params['access_token'] = $accessToken->getToken();
        $params['openid'] = $accessToken->getParam('openid');
        return $this->sendRequest($method, $url, $params, $headers);
    }

    protected function initUserAttributes() {
        return $this->api('sns/userinfo');
    }

    protected function defaultName() {
        return 'weixin';
    }

    protected function defaultTitle() {
        return '微信';
    }
}